package main

import (
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
)

const lenPath = len("/view/")

// 校验标题
var titleValidator = regexp.MustCompile("^[a-zA-Z0-9]+$")
var templates = make(map[string]*template.Template)
var err error

type Handler func(http.ResponseWriter, *http.Request, string)

type Page struct {
	Title string
	Body  []byte
}

// 保存结构体到txt文件
func (p *Page) Save() error {
	filename := p.Title + ".txt"

	return ioutil.WriteFile(filename, p.Body, 0600)
}

// 加载文件内容到Page结构体
func load(title string) (*Page, error) {
	filename := title + ".txt"
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return &Page{title, data}, nil

}

// 加载view, edit模板到templates
func init() {
	for _, tmp := range []string{"edit", "view"} {
		templates[tmp] = template.Must(template.ParseFiles(tmp + ".html"))
	}
}

// 包装handler, 解析路径为title并传入handler
func makeHandler(hd Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		title := r.URL.Path[lenPath:]
		if !titleValidator.MatchString(title) {
			http.NotFound(w, r)
			return
		}
		hd(w, r, title)
	}
}

// 渲染模板
func renderTemplate(w http.ResponseWriter, templ string, p *Page) {
	err := templates[templ].Execute(w, p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func viewhandler(w http.ResponseWriter, r *http.Request, title string) {
	// 加载文章到结构体
	p, err := load(title)
	if err != nil {
		// 没有文章则直接转到编辑
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}
	renderTemplate(w, "view", p)
}

func editHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := load(title)
	if err != nil {
		p = &Page{Title: title}
	}
	renderTemplate(w, "edit", p)
}

func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
	body := r.FormValue("body")
	p := &Page{Title: title, Body: []byte(body)}
	if err := p.Save(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 重定向到view
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

func main() {
	http.HandleFunc("/view/", makeHandler(viewhandler))
	http.HandleFunc("/edit/", makeHandler(editHandler))
	http.HandleFunc("/save/", makeHandler(saveHandler))
	if err := http.ListenAndServe(":9999", nil); err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}
}
